const axios = require('axios');

const BASE_URL = 'http://localhost:5000/api';
let authToken = '';

// 测试用例
const testCases = [
  {
    name: '时间调整建议',
    suggestion: {
      id: 'test_1',
      content: '建议将任务调整到明天下午3点完成',
      type: 'time_adjustment'
    },
    action: 'adjust_date',
    taskContext: {
      id: 'task_1',
      title: '完成项目报告',
      priority: 'P2',
      category: 'work',
      completed: false,
      dueDate: '2024-01-15T10:00:00.000Z'
    }
  },
  {
    name: '优先级提升建议',
    suggestion: {
      id: 'test_2',
      content: '这个任务比较紧急，建议提升优先级',
      type: 'priority_adjustment'
    },
    action: 'elevate_priority',
    taskContext: {
      id: 'task_2',
      title: '客户会议准备',
      priority: 'P2',
      category: 'work',
      completed: false,
      dueDate: '2024-01-16T14:00:00.000Z'
    }
  },
  {
    name: '具体时间建议',
    suggestion: {
      id: 'test_3',
      content: '建议调整到15:30完成',
      type: 'time_adjustment'
    },
    action: 'adjust_to_15_30',
    taskContext: {
      id: 'task_3',
      title: '团队会议',
      priority: 'P1',
      category: 'work',
      completed: false,
      dueDate: '2024-01-15T16:00:00.000Z'
    }
  },
  {
    name: '状态变更建议',
    suggestion: {
      id: 'test_4',
      content: '任务已经准备就绪，可以开始执行了',
      type: 'status_change'
    },
    action: 'mark_in_progress',
    taskContext: {
      id: 'task_4',
      title: '数据分析',
      priority: 'P1',
      category: 'work',
      completed: false,
      dueDate: '2024-01-17T18:00:00.000Z'
    }
  },
  {
    name: '复杂时间建议',
    suggestion: {
      id: 'test_5',
      content: '考虑到你的工作习惯，建议推迟到下周一下午2点',
      type: 'time_adjustment'
    },
    action: 'postpone',
    taskContext: {
      id: 'task_5',
      title: '季度总结',
      priority: 'P0',
      category: 'work',
      completed: false,
      dueDate: '2024-01-15T12:00:00.000Z'
    }
  }
];

async function login() {
  try {
    console.log('🔐 登录获取认证令牌...');
    const response = await axios.post(`${BASE_URL}/auth/login/email`, {
      email: 'admin@aide.com',
      password: 'admin123456'
    });
    
    if (response.data.token) {
      authToken = response.data.token;
      console.log('✅ 登录成功');
      return true;
    } else {
      console.log('❌ 登录失败:', response.data);
      return false;
    }
  } catch (error) {
    console.error('❌ 登录失败:', error.response?.data || error.message);
    return false;
  }
}

async function testActionParsing() {
  console.log('🧪 开始测试AI智能动作参数解析...\n');
  
  if (!await login()) {
    console.log('❌ 无法继续测试，登录失败');
    return;
  }
  
  for (const testCase of testCases) {
    try {
      console.log(`📝 测试: ${testCase.name}`);
      console.log(`   建议内容: "${testCase.suggestion.content}"`);
      console.log(`   动作: ${testCase.action}`);
      console.log(`   任务: ${testCase.taskContext.title}`);
      
      const response = await axios.post(`${BASE_URL}/ai/parse-action-parameters`, {
        suggestion: testCase.suggestion,
        action: testCase.action,
        taskContext: testCase.taskContext
      }, {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${authToken}`
        }
      });
      
      if (response.data.success) {
        const result = response.data.result;
        console.log('✅ 解析成功');
        console.log(`   参数:`, JSON.stringify(result.parameters, null, 4));
        console.log(`   推理: ${result.reasoning}`);
        console.log(`   置信度: ${Math.round(result.confidence * 100)}%`);
        console.log(`   需要用户输入: ${result.requiresUserInput}`);
        if (result.userPrompt) {
          console.log(`   用户提示: ${result.userPrompt}`);
        }
      } else {
        console.log('❌ 解析失败:', response.data);
      }
      
    } catch (error) {
      console.error(`❌ 测试失败: ${testCase.name}`, error.response?.data || error.message);
    }
    
    console.log('');
  }
  
  console.log('🎉 AI智能动作参数解析测试完成！');
}

async function testBatchParsing() {
  console.log('🧪 开始测试批量动作参数解析...\n');
  
  if (!await login()) {
    console.log('❌ 无法继续测试，登录失败');
    return;
  }
  
  try {
    const suggestions = testCases.map(testCase => ({
      id: testCase.suggestion.id,
      content: testCase.suggestion.content,
      type: testCase.suggestion.type,
      actions: [
        { label: '执行', action: testCase.action, primary: true }
      ]
    }));
    
    console.log(`📝 批量解析 ${suggestions.length} 个建议的动作参数...`);
    
    const response = await axios.post(`${BASE_URL}/ai/batch-parse-actions`, {
      suggestions: suggestions,
      taskContext: testCases[0].taskContext // 使用第一个任务的上下文作为示例
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authToken}`
      }
    });
    
    if (response.data.success) {
      console.log('✅ 批量解析成功');
      response.data.results.forEach((result, index) => {
        console.log(`\n   建议 ${index + 1}: ${testCases[index].name}`);
        if (result.success) {
          console.log(`   动作: ${result.action}`);
          console.log(`   参数:`, JSON.stringify(result.result.parameters, null, 4));
          console.log(`   推理: ${result.result.reasoning}`);
          console.log(`   置信度: ${Math.round(result.result.confidence * 100)}%`);
        } else {
          console.log(`   ❌ 解析失败: ${result.error}`);
        }
      });
    } else {
      console.log('❌ 批量解析失败:', response.data);
    }
    
  } catch (error) {
    console.error('❌ 批量解析测试失败:', error.response?.data || error.message);
  }
  
  console.log('\n🎉 批量解析测试完成！');
}

async function runAllTests() {
  console.log('🚀 开始全面测试AI智能动作参数解析功能...\n');
  
  await testActionParsing();
  console.log('\n' + '='.repeat(60) + '\n');
  await testBatchParsing();
  
  console.log('\n🎉 所有测试完成！');
}

runAllTests().catch(console.error);
